import React, { useState } from 'react'
import { MinusCircleOutlined } from '@ant-design/icons'
import { useDispatch, useSelector } from 'react-redux'

import classes from './Counter.module.css'
import { updPickedMeals } from '../../../redux/slices/counter'

const Counter = props => {
	const [count, setCount] = useState(props.pickedNum)

	const dispatch = useDispatch()
	const pickedMeals = [...useSelector(state => state.counter.value)]
	const mealData = { ...props.mealData, pickedNum: count }

	const addHandler = () => {
		if (count > 0) {
			pickedMeals.pop()
			dispatch(updPickedMeals(pickedMeals))
		}
		setCount(prevState => prevState + 1)
		const newMealData = { ...mealData, pickedNum: count * 1 + 1 }
		pickedMeals.push(newMealData)

		dispatch(updPickedMeals(pickedMeals))
	}
	const delHandler = () => {
		if (count === 1) {
			setCount(0)
			pickedMeals.pop()
			dispatch(updPickedMeals(pickedMeals))

			return
		}

		pickedMeals.pop()
		setCount(prevState => prevState - 1)
		const newMealData = { ...mealData, pickedNum: count * 1 - 1 }
		pickedMeals.push(newMealData)

		dispatch(updPickedMeals(pickedMeals))
	}

	return (
		<div className={classes.CounterContainer}>
			<div className={classes.CounterWrap}>
				{count === 0 ? null : (
					<>
						<MinusCircleOutlined onClick={delHandler} />
						<span className={classes.CounterCount}>{count}</span>
					</>
				)}
				<span className={classes.CounterPlus} onClick={addHandler}>
					<span>+</span>
				</span>
			</div>
		</div>
	)
}

export default Counter
